﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Web.Mvc;

namespace Willow.MVC.Search
{
    public class SearchModelBinder : IModelBinder
    {
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            var model = (QueryModel)(bindingContext.Model ?? new QueryModel());
            var dict = controllerContext.HttpContext.Request.Params;
            var keys = dict.AllKeys.Where(c => c.StartsWith("[")).ToList();
            if (keys.Count() != 0)
            {
                foreach (var key in keys)
                {
                    if (!key.StartsWith("[")) continue;
                    var val = dict[key];

                    if (string.IsNullOrEmpty(val))
                    {
                        continue;
                    }
                    AddSearchItem(model, key, val);
                }
            }
            return model;
        }

        /// <summary>
        /// 添加查询项
        /// </summary>
        /// <param name="model">The model.</param>
        /// <param name="key">The key.</param>
        /// <param name="val">The val.</param>
        private void AddSearchItem(QueryModel model, string key, string val)
        {
            string field = "", orGroup = "", method = "";
            var regmethod = Regex.Match(key, @"(?<=\[).*(?=])");
            method = regmethod.Success ? regmethod.Value : "";
            var regorGroup = Regex.Match(key, @"(?<={).*(?=})");
            orGroup = regorGroup.Success ? regorGroup.Value : "";
            var regfield = Regex.Matches(key, @"(\[.*(}|]))(?<field>.*)");
            field = regfield.Count > 0 ? regfield[0].Groups["field"].Value : "";
            if (string.IsNullOrEmpty(method) || string.IsNullOrEmpty(field)) return;

            object Value = val.Trim();

            string[] strval = val.Split(',');
            if (strval.Length > 0 && method == QueryMethod.StdIn.ToString())
            {
                Value = strval;
            }

            var item = new ConditionItem
            {
                Field = field,
                Value = Value,
                OrGroup = orGroup,
                Method = (QueryMethod)Enum.Parse(typeof(QueryMethod), method)
            };
            model.Items.Add(item);
        }
    }
}
